package com.fuyin.service.api;

import com.fuyin.commons.exception.ApiException;
import com.fuyin.commons.response.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author yuanxilan (yuanxilan@keep.com)
 * @Description
 * @date 2021年11月04日 4:40 下午
 * @since
 */
@Service
@Slf4j
public class PythonApiService {

    private static final String CODE_ADDRESS = "127.0.0.1";
    private static final Integer PORT = 9007;

    public void saveData(String gpName) {
        try (Socket socket = new Socket(CODE_ADDRESS, PORT)) {
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            outputStream.write(gpName.getBytes());
            int len = inputStream.read(bytes);
            String str = new String(bytes, 0, len);
            if ("400".equals(str)) {
                throw new ApiException("传入的股票名字有误");
            }
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("com.fuyin.service.api.PythonApiService.saveData e: {}, gpName: {}", e.getMessage(), gpName);
            throw new ApiException(ErrorCode.GP_NOT_SUPPORTED, "暂时不支持该股票的爬取");
        }
    }

}
